import Skeleton from 'taro-skeleton'
import {ComponentClass} from 'react'
import {AtSearchBar} from 'taro-ui'
import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Block, Image, Navigator, Text, View} from '@tarojs/components'
import {CityLocation} from '../utils/server.interface'
import {http} from '../utils/http'
import {
  MOVIE_CINEMAS,
  MOVIE_MOVIES,
  RESOURCE_URL,
} from '../constants/api'
import MovieHeaderBar from "./header-bar/movie-header-bar";
import {debounce, getHeadTop} from "../utils/tools";
import Cinema from "./cinema/cinema";
import {h5Wx} from "../utils/h5.service";
import GzhAuth from "../components/gzh-auth/gzh-auth"
import './index.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  searchKey: string
  movieList: any
  cinemaList: any
  searchBarTop: number
  location: any
  ML: any
  loading: boolean
  tabIndex: number
  scrollTop: any
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Movie {
  props: IProps
}

class Movie extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    movieList: [],
    cinemaList: [],
    searchKey: '',
    searchBarTop: 0,
    location: null,
    ML: {},
    loading: true,
    tabIndex: 0,
    scrollTop: [0, 0]
  }
  page = 1

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const ML = Taro.getStorageSync("ML");
    if (location.region_id == 0 || location.region_id == undefined) {
      Taro.navigateTo({
        url: "/other/select-city/movie-city"
      })
      return
    }
    this.setState({location, ML})
    const ret = await this.getData(location.region_id, ML)
    if (ret) {
      this.setState({
        movieList: ret.movieList, loading: false
      })
    } else {
      this.setState({
        loading: false
      })
    }

  }

  async componentDidShow() {
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const ML = Taro.getStorageSync("ML");
    const msg = await this.getCFData(this.page, location.region_id, ML)
    if (msg) {
      this.setState({
        cinemaList: msg.cinemaList
      })
    }
    this.setState({location})
  }

  async getData(cityId, ML) {
    const searchKey = this.state.searchKey
    const list = await http.MGet(MOVIE_MOVIES, {type: 1, cityId, lng: ML.lng, lat: ML.lat, movieName: searchKey})
    return list
  }

  async search() {
    const {tabIndex} = this.state
    Taro.showLoading({title: '加载中...'})
    if (tabIndex) {
      this.page = 1
      this.setState({
        loadMoreStatus: 'loading'
      })
      const {location, ML} = this.state
      const ret = await this.getCData(1, location.region_id, ML);
      Taro.hideLoading()
      if (ret && ret.cinemaList && ret.cinemaList.length > 0) {
        this.setState({loadMoreStatus: 'more', cinemaList: ret.cinemaList})
      } else {
        this.setState({loadMoreStatus: 'noMore', cinemaList: []})
        Taro.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
      }
    } else {
      const {location, ML} = this.state
      const ret = await this.getData(location.region_id, ML);
      Taro.hideLoading()
      if (ret && ret.movieList && ret.movieList.length > 0) {
        this.setState({
          movieList: ret.movieList
        })
      } else {
        this.setState({
          movieList: []
        })
        Taro.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
      }
    }

  }

  input(value) {
    if (value) {
      this.setState({searchKey: value})
    }
  }

  clearSearch() {
    this.setState({searchKey: ''}, async () => {
      this.search()
    })
  }

  onTabe() {
    const tabIndex = this.state.tabIndex
    this.setState({searchKey: ''})
    if (tabIndex) {
      this.setState({
        tabIndex: 0
      }, () => {
        this.goTop(0)
      })

    } else {
      this.setState({
        tabIndex: 1
      }, () => {
        this.goTop(1)
      })

    }

  }

  async getCFData(page, cityId, ML) {
    const searchKey = this.state.searchKey
    const List = await http.MGet(MOVIE_CINEMAS, {
      page,
      count: 20 * page,
      cityId,
      lng: ML.lng,
      lat: ML.lat,
      cinemaName: searchKey
    })
    if (List && List.cinemaList.length >= 20) {
      this.page++
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return List
  }

  async getCData(page, cityId, ML) {
    const searchKey = this.state.searchKey
    const List = await http.MGet(MOVIE_CINEMAS, {
      page,
      count: 20,
      cityId,
      lng: ML.lng,
      lat: ML.lat,
      cinemaName: searchKey
    })
    if (List && List.cinemaList.length >= 20) {
      this.page++
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return List
  }

  async joinMore() {
    const {location, ML} = this.state
    const oldList = this.state.cinemaList
    const msg = await this.getCData(this.page, location.region_id, ML)
    if (msg) {
      this.setState({
        cinemaList: [...oldList, ...msg.cinemaList]
      })
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore' && this.state.tabIndex) {
      this.joinMore()
    }
  }

  goTop(index) {  // 一键回到顶部
    const {scrollTop} = this.state
    if (Taro.pageScrollTo) {//判断这个方法是否可用
      Taro.pageScrollTo({
        scrollTop: scrollTop[index]
      })
    } else {
      Taro.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  }

  onPageScroll = debounce((scroll) => {
    const {scrollTop, tabIndex} = this.state
    scrollTop[tabIndex] = scroll[0].scrollTop
    this.setState({
      scrollTop
    })
  })

  render() {
    const {loading, loadMoreStatus, searchBarTop, searchKey, movieList, location, tabIndex, cinemaList} = this.state
    return (
      <View className='moveList'>
        <GzhAuth />
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <MovieHeaderBar onTabe={this.onTabe.bind(this)} index={tabIndex}></MovieHeaderBar>
        </View>
        <View className='haeder'>
          <Navigator className='add-city' url='/other/select-city/movie-city' hoverClass='none'>
            {location.area_name}
          </Navigator>
          <View className='search-box'>
            <AtSearchBar className='search' onConfirm={this.search.bind(this)} onClear={this.clearSearch.bind(this)}
              onActionClick={this.search.bind(this)} value={searchKey} onChange={this.input.bind(this)}
              placeholder={tabIndex ? "搜索影院" : "搜索电影"}
            ></AtSearchBar>
          </View>
        </View>
        <Skeleton loading={loading} row={4} rowHeight={150}>
          <Block>
            {tabIndex == 0 && <View className='movie-box'>
              {movieList && movieList.length > 0 && movieList.map((item, index) =>
                <Navigator url={"/movie/Minfo?id=" + item.std_id} hoverClass='none' className='movin-item'
                  key={index}
                >
                  <View><Image className='movin-img' src={RESOURCE_URL + item.poster} mode='aspectFill'></Image></View>
                  <View className='movin-right'>
                    <View className='movin-info'>
                      <View className='movin-name'>{item.name}</View>
                      <View className='movin-score'>评分: <Text>{item.grade ? item.grade : '暂无评分'}</Text></View>
                      <View className='movin-star'>主演: {item.cast}</View>
                      <View className='movin-time'>{item.publish_area}/{item.duration}分钟</View>
                    </View>
                    <View className='movin-buy' url={"/movie/Minfo?id=" + item.std_id}>购票</View>
                  </View>
                </Navigator>
              )}
              {movieList.length == 0 && <View className='sessions-box-none'>暂无影片</View>}
            </View>}
            {tabIndex == 1 &&
            <Block>
              <View className='cinema-box'>
                {cinemaList.length > 0 ? <Cinema data={cinemaList}></Cinema> :
                  <View className='sessions-box-none'>暂无该影院</View>}
              </View>
            </Block>
            }
          </Block>
        </Skeleton>
      </View>
    )
  }
}

export default Movie as ComponentClass<PageOwnProps, PageState>
